using System;
using System.Collections;
using System.Collections.Generic;

namespace Tycho.Parser.Peg {
    public class DynamicChoiceProduction : Production {
        protected override Yield ReallyParse(char[] source, int index, ParseContext context, string sourceString, ParseEnvironment parseEnvironment, Func<ParseResult, Yield> continuation)
        {
            return ParseProduction(context.DynamicGrammar.GetChoices(this).GetEnumerator(), source, index, parseEnvironment, context, sourceString, continuation);
        }

        private Yield ParseProduction(IEnumerator productionEnumerator, char[] source, int index, ParseEnvironment parseEnvironment, ParseContext context, string sourceString, Func<ParseResult, Yield> continuation)
        {
            if (productionEnumerator.MoveNext())
            {
                IProduction p = (IProduction)productionEnumerator.Current;
                return p.Parse(source, index, context, sourceString, parseEnvironment, result =>
                {
                    if (result != null)
                    {
                        return () => continuation(result);
                    }
                    else
                    {
                        return () => ParseProduction(productionEnumerator, source, index, parseEnvironment, context, sourceString, continuation);
                    }
                });
            }
            else
            {
                return () => continuation(null);
            }
        }
    }
}